<template>
  <div class="my-m mx-m h-full overflow-y-auto m-relative pt-12n">
    <div class="flex w-fit flex-j-c m-fixed t-28n z-index-9999 position-center-x">
      <div class="screen-box round-8 h-10n bgfff w-fit flex-center px-20">
        <a-input-group>
          <a-select
            :style="{ width: 'fit-content' }"
            :trigger-props="{ autoFitPopupMinWidth: true }"
            v-model="commonParam.sourceChatroomId"
            @change="getTopData"
          >
            <a-option value="" label="全部源头群" />
            <a-option
              v-for="item in sourceList"
              :key="item.sourceChatRoomId"
              :value="item.sourceChatRoomId"
              :label="item.name"
            />
          </a-select>
          <a-divider direction="vertical" />
          <a-select
            :style="{ width: 'fit-content' }"
            :trigger-props="{ autoFitPopupMinWidth: true }"
            v-model="commonParam.platformId"
            @change="getTopData"
          >
            <a-option value="" label="全部平台" />
            <a-option
              v-for="item in platformList"
              :key="item.sourceType"
              :value="item.sourceType"
              :label="item.title"
            />
          </a-select>
          <a-divider direction="vertical" />
          <ms-date
            class="w-60n"
            v-model:start="commonParam.startAt"
            :disabledDate="
              (current) =>
                dayjs(current).isAfter(dayjs().endOf('date')) ||
                dayjs(current).isBefore(dayjs('2023-09-07').startOf('date'))
            "
            v-model:end="commonParam.endAt"
            :showQuick="true"
            @dateChange="getTopData"
          ></ms-date>
          <a-button type="text" size="mini" @click="handleUpdateData">
            <icon-refresh />
            更新时间：{{ renew }}
          </a-button>
        </a-input-group>
      </div>
    </div>
    <a-spin class="w-full mt-10n" :loading="loading">
      <div class="flex flex-wrap w-full pl-10 box-border">
        <ms-data-card title="总GMV（元）" :value="amountData.totalGmv" :precision="2"></ms-data-card>
        <ms-data-card title="有效GMV（元）" :value="amountData.validGmv" :style="2" :precision="2"></ms-data-card>
        <ms-data-card
          title="总订单量（单）"
          :value="amountData.totalOrderCount"
          :style="3"
          :precision="0"
        ></ms-data-card>
        <ms-data-card
          title="有效订单（单）"
          :value="amountData.validOrderCount"
          :style="4"
          :precision="0"
        ></ms-data-card>
        <ms-data-card
          title="失效订单（单）"
          :value="amountData.invalidOrderCount"
          :style="5"
          :precision="0"
        ></ms-data-card>
        <ms-data-card
          title="预估佣金（元）"
          :value="amountData.totalCommission"
          :style="6"
          :precision="2"
        ></ms-data-card>
        <ms-data-card
          title="商品总数（个）"
          :value="amountData.totalGoodsCount"
          :style="7"
          :precision="0"
        ></ms-data-card>
      </div>
      <div class="w-full mt-20 bgfff p-m box-border">
        <GiTable
          row-key="id"
          id="groupOrderStatistics"
          v-model:columns="columns"
          :data="tableData"
          :scroll="{ x: '100%', y: false, minWidth: 1000 }"
          :pagination="false"
          @refresh="getTopData"
        >
          <template #sourceChatName="{ record }">
            <div class="text-overflow-2 text-theme cursor-pointer" @click="toItem(record)">
              {{ record.sourceChatName }}
            </div>
          </template>
        </GiTable>
      </div>
    </a-spin>
  </div>
</template>

<script setup>
import dayjs from 'dayjs'
import { usePlatform, useSource } from '@/hooks/app'
import { sourceChatRoomOrderData } from '@/apis'
import { deleteEmpty } from '@/utils/common'
import { reAssign } from '@/utils/common'
import { Message } from '@arco-design/web-vue'

defineOptions({ name: 'groupOrderStatistics' })
const renew = ref(dayjs().format('YYYY.MM.DD HH:mm:ss'))
const tableData = ref([])
const loading = ref(false)
const router = useRouter()

// 公共参数
const commonParam = ref({
  startAt: dayjs().subtract(7, 'day').startOf('day').format('YYYY-MM-DD HH:mm:ss'),
  endAt: dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss'),
  sourceChatroomId: '',
  platformId: ''
})

const amountData = ref({
  invalidOrderCount: 0,
  totalCommission: 0,
  totalGmv: 0,
  totalGoodsCount: 0,
  totalOrderCount: 0,
  validGmv: 0,
  validOrderCount: 0
})

const columns = ref([
  {
    title: '群名称',
    width: 200,
    slotName: 'sourceChatName'
  },
  {
    title: '日期',
    width: 180,
    align: 'center',
    render: () => {
      return `${commonParam.value.startAt}\n${commonParam.value.endAt}`
    }
  },
  {
    title: '平台',
    width: 180,
    align: 'center',
    dataIndex: 'platformAll'
  },
  {
    title: 'GMV(元)',
    width: 130,
    align: 'center',
    dataIndex: 'totalGmv',
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: '有效GMV(元)',
    width: 130,
    align: 'center',
    dataIndex: 'validGmv',
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: '订单量(单)',
    width: 130,
    align: 'center',
    dataIndex: 'totalOrderCount',
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: '有效订单量(单)',
    width: 130,
    align: 'center',
    dataIndex: 'validOrderCount',
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: '失效订单量(单)',
    width: 130,
    align: 'center',
    dataIndex: 'invalidOrderCount',
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: '预估佣金(元)',
    width: 130,
    align: 'center',
    dataIndex: 'totalCommission',
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: '商品数(个)',
    width: 130,
    align: 'center',
    dataIndex: 'totalGoodsCount',
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  }
])

// 获取源头群
const { sourceList, getSourceList } = useSource()
getSourceList()

// 获取平台
const { platformList, getPlatformList } = usePlatform()
getPlatformList()

// 获取头部信息
const getTopData = async () => {
  try {
    loading.value = true
    const param = {
      startAt: dayjs(commonParam.value.startAt).startOf('day').format('YYYY-MM-DD HH:mm:ss'),
      endAt: dayjs(commonParam.value.endAt).endOf('day').format('YYYY-MM-DD HH:mm:ss'),
      sourceChatroomId: commonParam.value.sourceChatroomId,
      platformId: commonParam.value.platformId
    }
    const res = await sourceChatRoomOrderData(deleteEmpty(param))
    amountData.value = reAssign(amountData.value, res.data.totalDta)
    if (res.data.totalDta) {
      const totalDta = res.data.totalDta
      for (const key in amountData.value) {
        if (totalDta[key]) {
          amountData.value[key] = Number(totalDta[key])
        }
      }
    }
    tableData.value = res.data.sourceChatroomData.map((item, index) => {
      let platform = ''
      if (item.platforms && item.platforms.length) {
        item.platforms.forEach((element) => {
          platform += `${element.name}、`
        })
      }
      return {
        ...item,
        id: index + 100,
        platformAll: platform ? platform.slice(0, -1) : '--'
      }
    })
    renew.value = dayjs().format('YYYY-MM-DD HH:mm:ss')
  } finally {
    loading.value = false
  }
}
getTopData()

const handleUpdateData = async () => {
  await getTopData()
  Message.success('刷新成功')
}

// 跳转详情
const toItem = (record) => {
  router.push({
    path: '/group/groupUserOrder',
    query: {
      ...commonParam.value,
      sourceChatroomId: record.sourceChatroomId
    }
  })
}
</script>

<style lang="scss" scoped>
.screen-box {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  :deep(.arco-select-view, .arco-picker) {
    border: none;
  }
  :deep(.arco-picker) {
    border: none;
  }
  :deep(.arco-divider-vertical) {
    margin: 0;
  }
}
</style>
